#!/usr/bin/env bash

# Toggle terminal to show up as a popup terminal
# by Adnan Shameem (adnan360); License: MIT (Expat)
#
# Requirements:
# - any terminal emulator (xterm, lxterminal etc.)
# - xdotool
# - wmctrl
#
# Usage:
# - Change configs below as you wish
# - Run the script: ./popup-terminal.sh
#   or bind it on a key

# Config
config_term_program='{{@@ terminal_exec @@}}'
config_term_width=800
config_term_height=300
config_top_decoration_height=30

# Temporary files
widfile='/tmp/openbox_config_popup_term_wid'
visiblefile='/tmp/openbox_config_popup_term_visible'

# Position and prepare the terminal window
# Params:
# - $1: Window ID of the terminal
prepare_term() {
	screen_width=$(xdpyinfo | awk '/dimensions:/{print $2 }' | cut -d 'x' -f1)
	# Set window title
	xdotool set_window --name 'My Popup Terminal' "$1"
	# Size and position the terminal window to top center
	xdotool windowmove "$1" $(( ($screen_width - $config_term_width) / 2 )) -$config_top_decoration_height
	xdotool windowsize "$1" $config_term_width $config_term_height
	# Needs to be focused to, in order to fix a weird bug which doesn't make
	# always on top work when last window is maximized.
	xdotool windowfocus --sync "$1"
	# Always on top
	wmctrl -r :ACTIVE: -b add,above
}

# Terminal not running, we need to start terminal
if [ -z "$(xdotool getwindowpid $(cat "$widfile") 2>/dev/null)" ]; then
	prevfocus=$(xdotool getactivewindow)
	$config_term_program &>/dev/null & disown
	# Sleep until terminal opens and then we continue...
	until [ "$(xdotool getactivewindow)" != "$prevfocus" ]; do
		sleep 1
	done
	# When terminal opens, we store the Window ID
	wid=$(xdotool getactivewindow)
	echo "$wid"> "$widfile"
	prepare_term "$wid"
	touch "$visiblefile"
# Terminal is already there, we just need to show/hide it
else
	if [ ! -f "$visiblefile" ]; then
		wid=$(cat "$widfile")
		xdotool windowmap --sync "$wid"
		prepare_term "$wid"
		touch "$visiblefile"
	else
		wid=$(cat "$widfile")
		xdotool windowunmap --sync "$wid"
		rm "$visiblefile"
	fi
fi

